﻿using GComp.Apps.EasyStock.Common;
using GComp.Apps.EasyStock.Data;
using GComp.Apps.EasyStock.DataModel;
using GComp.Apps.EasyStock.DataModel.Common;
using GComp.Apps.EasyStock.DataModel.Search;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Item Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234232

namespace GComp.Apps.EasyStock.Controls {
    /// <summary>
    /// A page that displays details for a single item within a group while allowing gestures to
    /// flip through other items belonging to the same group.
    /// </summary>
    public sealed partial class AddNewPage : GComp.Apps.EasyStock.Common.LayoutAwarePage {
        public AddNewPage() {
            this.InitializeComponent();
            SetUp();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) {
            // Allow saved page state to override the initial item to display
            if (pageState != null && pageState.ContainsKey("SelectedItem")) {
                navigationParameter = pageState["SelectedItem"];
            }

            // TODO: Assign a bindable group to this.DefaultViewModel["Group"]
            // TODO: Assign a collection of bindable items to this.DefaultViewModel["Items"]
            // TODO: Assign the selected item to this.flipView.SelectedItem
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState) {
            //var selectedItem = this.flipView.SelectedItem;
            // TODO: Derive a serializable navigation parameter and assign it to pageState["SelectedItem"]
        }

        private void OnBtnOKGroups_Click(object sender, RoutedEventArgs e) {
            AddGroup();
            OnClearGroup();
            //this.Frame.Navigate(typeof(GroupsOverview), "AllGroups");
        }

        private void AddGroup() {
            StockGroup group = new StockGroup {
                Name = tbGroupTitle.Text,
                Description = tbGroupDescription.Text
            };
            DataManager.Instance.Groups.Add(group);
            DataModel.DataContext.Instance.UIData.AllGroups.Insert(DataModel.DataContext.Instance.UIData.AllGroups.Count - 1, DataModel.DataContext.CreateFromDataGroup(group));
            EntriesChanged();
        }

        private void btnOkStock_Click(object sender, RoutedEventArgs e) {
            SampleDataGroup group = cbGroups.SelectedItem as SampleDataGroup;

            if (group != null) {
                StockGroup dataGroup = DataManager.Instance.Groups[group.UniqueId];
                StockEntry entry = new StockEntry {
                    Symbol = tbSymbol.Text, 
                    Name = string.IsNullOrEmpty(tbTitle.Text) ? tbSymbol.Text : tbTitle.Text
                };
                dataGroup.Entries.Add(entry);
                group.Items.Add(DataModel.DataContext.CreateItemFromEntry(group, entry));
                EntriesChanged();
            }
            OnClearStock();
        }

        private void OnClearStock() {
            cbGroups.SelectedItem = null;
            tbSymbol.Text = "";
            tbTitle.Text = "";
            tbSearch.Text = "";
            lvResults.DataContext = null;
        }

        private BackgroundWorkState state;
        private SymbolListManager symbolsManager;

        private void SetUp() {
            state = new BackgroundWorkState();
            tbDownloadState.DataContext = state;

            symbolsManager = new SymbolListManager();
            symbolsManager.WorkState = state;
            symbolsManager.DownloadAll();

            EntriesChanged();
        }

        private void EntriesChanged() {
            cbDeleteStocks.DataContext = null;
            cbDeleteGroups.DataContext = DataModel.DataContext.Instance.UIData.AllGroups.Where(g => g.UniqueId != "EasyStock.Common.Add");
            cbDeleteStocks.DataContext = DataModel.DataContext.Instance.UIData.AllStocks;
            cbGroups.DataContext = DataModel.DataContext.Instance.UIData.AllGroups.Where(g => g.UniqueId != "EasyStock.Common.Add");
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e) {
            Search();
        }

        private async void Search() {
            List<StockEntry> entries = await symbolsManager.Search(tbSearch.Text);
            lvResults.DataContext = entries;
        }

        private void btnClearGroup_Click(object sender, RoutedEventArgs e) {
            OnClearGroup();
        }

        private void OnClearGroup() {
            this.tbGroupTitle.Text = "";
            this.tbGroupDescription.Text = "";
        }

        private void btnDeleteGroup_Click_1(object sender, RoutedEventArgs e) {
            SampleDataGroup group = cbDeleteGroups.SelectedItem as SampleDataGroup;

            DataManager.Instance.Groups.RemoveAll((g) => g.Id == group.UniqueId);
            DataModel.DataContext.Instance.UIData.AllGroups.Remove(group);

            OnClearDeleteGroup();
            EntriesChanged();
        }

        private void OnClearDeleteGroup() {
            cbDeleteGroups.SelectedItem = null;
        }

        private void btnDeleteStock_Click(object sender, RoutedEventArgs e) {
            SampleDataItem group = cbDeleteStocks.SelectedItem as SampleDataItem;

            if (group != null) {
                group.Group.Items.Remove(group);
                StockGroup dataGroup = DataManager.Instance.Groups[group.Group.UniqueId];
                dataGroup.Entries.Remove(dataGroup.Entries.FirstOrDefault(entry => entry.Id == group.UniqueId));

                EntriesChanged();
            }

            OnClearDeleteEntry();
        }

        private void OnClearDeleteEntry() {
            cbDeleteStocks.SelectedItem = null;
        }

        private void cbGroups_SelectionChanged_1(object sender, SelectionChangedEventArgs e) {
            CheckButtonAddStock();
        }

        private void tbSymbol_TextChanged_1(object sender, TextChangedEventArgs e) {
            CheckButtonAddStock();
        }

        private void CheckButtonAddStock() {
            btnOkStock.IsEnabled = cbGroups.SelectedItem != null && !string.IsNullOrEmpty(tbSymbol.Text);
        }
    }
}
